package com.hmall.service;

import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.DateTimeUtil;
import com.hdmall.business.common.util.IpUtil;
import com.hdmall.business.common.util.PhoneUtil;
import com.hmall.mapper.BiPvScheduleJobMapper;
import com.hmall.mapper.BiUserActionHistoryMapper;
import com.hmall.model.BiPvScheduleJob;
import com.hmall.model.BiUserActionHistory;
import com.hmall.model.SysUser;
import com.hdmall.business.common.vo.AddressResultVo;
import com.hmall.vo.BiActionHisParamsClientVo;
import com.hmall.vo.BiActionHisParamsVo;
import com.hmall.vo.DeviceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hdmall.business.common.util.JsonUtils.jsonStrToObject;

/**
 * 用户行为服务层
 */
@Service
public class BiUserActionHistoryService {
    @Autowired
    private BiUserActionHistoryMapper biUserActionHistoryMapper;
    @Autowired
    private BiPvScheduleJobMapper biPvScheduleJobMapper;

    //插入一个用户行为记录
    public ServerResponse insertActionHis(BiActionHisParamsVo biActionHisParams) {
        BiUserActionHistory actionHistory = new BiUserActionHistory();
        actionHistory.setAction(biActionHisParams.getAction());
        actionHistory.setActionUrl(biActionHisParams.getActionUrl());
        actionHistory.setContent(biActionHisParams.getContent());
        actionHistory.setUserRoleId(biActionHisParams.getUserRoleId());
        actionHistory.setUserRoleName(biActionHisParams.getUserRoleName());
        StringBuffer deviceSb = new StringBuffer();
        HttpServletRequest request = biActionHisParams.getRequest();
        SysUser user = biActionHisParams.getUser();
        String user_agent = request.getHeader("user-agent");
        if (user_agent != null) {
            if (user_agent.contains("device_name")) {
                DeviceVo deviceVo = jsonStrToObject(user_agent, DeviceVo.class);
                String deviceName = deviceVo.getDevice_name();
                String deviceDesc = deviceVo.getDevice_desc();
                String system = deviceVo.getSystem();
                //苹果
                if (deviceName.toLowerCase().contains("mac") || deviceName.toLowerCase().contains("ios")) {
                    actionHistory.setDeviceType(2);
                    deviceSb.append("IOS:" + deviceName + ";" + deviceDesc + ";" + system);
                    //安卓
                } else {
                    actionHistory.setDeviceType(1);
                    deviceSb.append("Android:" + deviceName + ";" + deviceDesc + ";" + system);
                    //PC
                }
            } else {
                actionHistory.setDeviceType(3);
                deviceSb.append("Pc:" + user_agent);

            }
            actionHistory.setDeviceName(deviceSb.toString());
        }

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        actionHistory.setIp(ip);
        AddressResultVo addressResult = IpUtil.getBaiduPosition(ip);
        if (addressResult.getStatus().equals("0")) {//状态0 正常
            String province = addressResult.getContent().getAddress_detail().getProvince();
            String city = addressResult.getContent().getAddress_detail().getCity();
            if (province != null && !"".equals(province)) {
                actionHistory.setProvince(province);
            }
            if (city != null && !"".equals(city)) {
                actionHistory.setCity(city);
            }
        }
        if (user != null) {
            actionHistory.setUserId(user.getUserId());
            //看是买方还是卖方
            if (user.getPhone() != null && !"".equals(user.getPhone()) && addressResult.getStatus().equals("0")) {
                actionHistory.setPhone(user.getPhone());
                String getZoneResult = PhoneUtil.calcMobileCity(user.getPhone());
                if (getZoneResult != null && !"".equals(getZoneResult)) {
                    String carrier = getZoneResult.substring(getZoneResult.indexOf("carrier") + "carrier".length() + 1, getZoneResult.length() - 1);
                    actionHistory.setPhoneProvince(carrier);
                }
            }
        }

        try {
            biUserActionHistoryMapper.insertUserActionHis(actionHistory);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.USER_BI_ACT_HIS_FOUND.getCode(), ResponseCode.USER_BI_ACT_HIS_FOUND.getDesc());
        }

        return ServerResponse.createBySuccess("用户历史插入成功");

    }

    //异步调用
    public ServerResponse insertActionHisByClient(BiActionHisParamsClientVo biActionHisParamsClientVo) {
        String user_agent = biActionHisParamsClientVo.getUserAgent();
        String ip = biActionHisParamsClientVo.getIp();
        SysUser user = biActionHisParamsClientVo.getUser();
        BiUserActionHistory actionHistory = new BiUserActionHistory();
        actionHistory.setAction(biActionHisParamsClientVo.getAction());
        actionHistory.setActionUrl(biActionHisParamsClientVo.getActionUrl());
        actionHistory.setContent(biActionHisParamsClientVo.getContent());
        actionHistory.setUserRoleId(biActionHisParamsClientVo.getUserRoleId());
        actionHistory.setUserRoleName(biActionHisParamsClientVo.getUserRoleName());
        actionHistory.setIp(ip);


        StringBuffer deviceSb = new StringBuffer();
        if (user_agent != null) {
            if (user_agent.contains("device_name")) {
                DeviceVo deviceVo = jsonStrToObject(user_agent, DeviceVo.class);
                String deviceName = deviceVo.getDevice_name();
                String deviceDesc = deviceVo.getDevice_desc();
                String system = deviceVo.getSystem();
                //苹果
                if (deviceName.toLowerCase().contains("mac") || deviceName.toLowerCase().contains("ios")) {
                    actionHistory.setDeviceType(2);
                    deviceSb.append("IOS:" + deviceName + ";" + deviceDesc + ";" + system);
                    //安卓
                } else {
                    actionHistory.setDeviceType(1);
                    deviceSb.append("Android:" + deviceName + ";" + deviceDesc + ";" + system);
                    //PC
                }
            } else {
                actionHistory.setDeviceType(3);
                deviceSb.append("Pc:" + user_agent);

            }
            actionHistory.setDeviceName(deviceSb.toString());
        }

        AddressResultVo addressResult = IpUtil.getBaiduPosition(ip);
        if (addressResult.getStatus().equals("0")) {//状态0 正常
            String province = addressResult.getContent().getAddress_detail().getProvince();
            String city = addressResult.getContent().getAddress_detail().getCity();
            if (province != null && !"".equals(province)) {
                actionHistory.setProvince(province);
            }
            if (city != null && !"".equals(city)) {
                actionHistory.setCity(city);
            }
        }
        if (user != null) {
            actionHistory.setUserId(user.getUserId());
            //看是买方还是卖方
            if (user.getPhone() != null && !"".equals(user.getPhone()) && addressResult.getStatus().equals("0")) {
                actionHistory.setPhone(user.getPhone());
                String getZoneResult = PhoneUtil.calcMobileCity(user.getPhone());
                if (getZoneResult != null && !"".equals(getZoneResult)) {
                    String carrier = getZoneResult.substring(getZoneResult.indexOf("carrier") + "carrier".length() + 1, getZoneResult.length() - 1);
                    actionHistory.setPhoneProvince(carrier);
                }
            }
        }

        try {
            biUserActionHistoryMapper.insertUserActionHis(actionHistory);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.USER_BI_ACT_HIS_FOUND.getCode(), ResponseCode.USER_BI_ACT_HIS_FOUND.getDesc());
        }

        return ServerResponse.createBySuccess("用户历史插入成功");

    }

    //查询三个月的记录
    public ServerResponse<List> selectThreeMonths() {
        List<BiUserActionHistory> biUserActionHistories;
        try {
            biUserActionHistories = biUserActionHistoryMapper.selectThreeMonths();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(211, "用户行为查询错误");
        }
        List<Object> list = new ArrayList<Object>();
        Map<String, Object> idsMap = new HashMap<String, Object>();
        List<Long> Ids = new ArrayList<Long>();

        Map<String, Object> ipMap = new HashMap<String, Object>();
        List<String> ips = new ArrayList<String>();

        Map<String, Object> provincesMap = new HashMap<String, Object>();
        List<String> provinces = new ArrayList<String>();

        Map<String, Object> citysMap = new HashMap<String, Object>();
        List<String> citys = new ArrayList<String>();

        Map<String, Object> userIdsMap = new HashMap<String, Object>();
        List<Integer> userIds = new ArrayList<Integer>();

        Map<String, Object> userRoleNamesMap = new HashMap<String, Object>();
        List<String> userRoleNames = new ArrayList<String>();

        Map<String, Object> deviceTypesMap = new HashMap<String, Object>();
        List<Integer> deviceTypes = new ArrayList<Integer>();

        Map<String, Object> deviceNamesMap = new HashMap<String, Object>();
        List<String> deviceNames = new ArrayList<String>();

        Map<String, Object> phoneProvincesMap = new HashMap<String, Object>();
        List<String> phoneProvinces = new ArrayList<String>();

        Map<String, Object> phonesMap = new HashMap<String, Object>();
        List<String> phones = new ArrayList<String>();

        Map<String, Object> createTimesMap = new HashMap<String, Object>();
        List<String> createTimes = new ArrayList<String>();

        Map<String, Object> actionsMap = new HashMap<String, Object>();
        List<String> actions = new ArrayList<String>();

        Map<String, Object> actionUrlsMap = new HashMap<String, Object>();
        List<String> actionUrls = new ArrayList<String>();

        Map<String, Object> contentsMap = new HashMap<String, Object>();
        List<String> contents = new ArrayList<String>();

        for (BiUserActionHistory biUserActionHistory : biUserActionHistories) {

            Ids.add(biUserActionHistory.getActionHisId());
            idsMap.put("Ids", Ids);
            ips.add(biUserActionHistory.getIp());
            ipMap.put("ips", ips);
            provinces.add(biUserActionHistory.getProvince());
            provincesMap.put("provinces", provinces);
            citys.add(biUserActionHistory.getCity());
            citysMap.put("citys", citys);
            userIds.add(biUserActionHistory.getUserId());
            userIdsMap.put("userIds", userIds);
            userRoleNames.add(biUserActionHistory.getUserRoleName());
            userRoleNamesMap.put("userRoleNames", userRoleNames);
            deviceTypes.add(biUserActionHistory.getDeviceType());
            deviceTypesMap.put("deviceTypes", deviceTypes);
            deviceNames.add(biUserActionHistory.getDeviceName());
            deviceNamesMap.put("deviceNames", deviceNames);
            phoneProvinces.add(biUserActionHistory.getProvince());
            phoneProvincesMap.put("phoneProvinces", phoneProvinces);
            phones.add(biUserActionHistory.getPhone());
            phonesMap.put("phones", phones);
            createTimes.add(DateTimeUtil.dateToStr(biUserActionHistory.getCreateTime()));
            createTimesMap.put("createTimes", createTimes);
            actions.add(biUserActionHistory.getAction());
            actionsMap.put("actions", actions);
            actionUrls.add(biUserActionHistory.getActionUrl());
            actionUrlsMap.put("actionUrls", actionUrls);
            contents.add(biUserActionHistory.getContent());
            contentsMap.put("contents", contents);
        }
        list.add(idsMap);
        list.add(ipMap);
        list.add(provincesMap);
        list.add(citysMap);
        list.add(userIdsMap);
        list.add(userRoleNamesMap);
        list.add(deviceTypesMap);
        list.add(deviceNamesMap);
        list.add(phoneProvincesMap);
        list.add(phonesMap);
        list.add(createTimesMap);
        list.add(actionsMap);
        list.add(actionUrlsMap);
        list.add(contentsMap);
        return ServerResponse.createBySuccess(list);
    }

    //插入当天的访问的用户PV 新用户 新特权用户等
    public void insertBiPvSchedule() {
        BiPvScheduleJob biPvScheduleJob = new BiPvScheduleJob();
        int userNum = biPvScheduleJobMapper.selectUserNum();
        int newUserNum = biPvScheduleJobMapper.selectNewUserNum();
        int superUserNum = biPvScheduleJobMapper.selectNewSuperUserNum();
        int visitNum = biPvScheduleJobMapper.selectVisitNum();
        biPvScheduleJob.setUserNum(userNum);
        biPvScheduleJob.setNewUserNum(newUserNum);
        biPvScheduleJob.setNewUserSuperNum(newUserNum);
        biPvScheduleJob.setVisitNum(visitNum);
        biPvScheduleJobMapper.insertBiPvJob(biPvScheduleJob);

    }



}
